//
//  HHomeViewController.m
//  Router
//
//  Created by Zhen Huang on 2017/2/7.
//  Copyright © 2017年 Zhen Huang. All rights reserved.
//

#import "HHomeViewController.h"
#import "RegisterAndLoginViewController.h"
#import "HRoutersViewController.h"
#import "HW3DBannerView.h"
#import "PGIndexBannerSubiew.h"
#import "NewPagedFlowView.h"
#import "HRouterModel.h"
#import "HTrendModel.h"
#import "HOutputModel.h"
#import "HHomeCollectionViewCell.h"
#import "TWRChart.h"
#import "FXCyclePagerViewCell.h"
#import "FXCyclePagerView.h"
#import "FXPageControl.h"
#import "Router-Bridging-Header.h"
#import "XLCycleCollectionView.h"
@interface HHomeViewController ()
<NewPagedFlowViewDelegate,
NewPagedFlowViewDataSource,
UITableViewDelegate,
UITableViewDataSource,
UICollectionViewDelegate,
UICollectionViewDataSource,
FXCyclePagerViewDataSource,
FXCyclePagerViewDelegate>
@property (nonatomic, strong) UIView *customTabber;
@property (nonatomic, strong) NSArray * titles;
@property (nonatomic, strong) NSArray * images;
@property (nonatomic, strong) NSArray * selectedImages;
@property (nonatomic, strong) NSMutableArray * buttons;
@property (nonatomic, strong) HHomeViewController *homeViewController;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) UITableView *tabelview;
@property (nonatomic, strong) UIView *tabelHeaderView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIScrollView *bottomScrollView;
@property (nonatomic, strong) HOutputModel *HoutModel;
@property (nonatomic, strong) HOutputModel *HoutModelYesterDay;
@property (nonatomic, strong) HOutputModel *HoutModelLastWeek;
@property (nonatomic, strong) HOutputModel *HoutModelLastMonth;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) HRouterModel *routerModel;
@property (nonatomic, strong) TWRChartView *chartView;
@property (nonatomic, strong) UILabel *dayLabel;
@property (nonatomic, strong) NSMutableArray *tendArray;
@property (nonatomic, strong) FXCyclePagerView *pagerView;
@property (nonatomic, strong) FXPageControl *pageControl;
@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) PieChartView *pieChartView;//Charts画图
@property (nonatomic, strong) PieChartData *data;//设置Charts的数据
@end

@implementation HHomeViewController
- (instancetype)init {
    if (self) {
        self.imageArray = [NSMutableArray new];
        self.tendArray = [NSMutableArray new];
        self.modelArray = [NSMutableArray new];
    }
    return self;
}
static NSString * const identifier = @"FXCyclePagerViewCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tabelview];
    self.view.backgroundColor = kBackGroundColor;
    [self GetRouter];
    [self GetTrend];
    [self getOutPutData];
}
- (void)getOutPutData {
    NSString *url = F(@"%@/counts/output?start_time=%@&end_time=%@", BaseUrl,[self getNDay:0]?:@"",[self getNDay:1]?:@"");
    NSString *Token = F(@"Token %@",  [[TMCache sharedCache] objectForKey:@"Token"]);
    [self receivePOSTWithTokenURLString:url method:@"GET" body:nil Token:Token Blocks:^(NSDictionary *tempData, NSInteger state) {
        self.HoutModelYesterDay = [HOutputModel yy_modelWithJSON:tempData];
        self.HoutModelYesterDay.title = @"昨日";
    }];
    NSString *url1 = F(@"%@/counts/output?start_time=%@&end_time=%@", BaseUrl,[self getNDay:-6]?:@"",[self getNDay:1]?:@"");
    [self receivePOSTWithTokenURLString:url1 method:@"GET" body:nil Token:Token Blocks:^(NSDictionary *tempData, NSInteger state) {
        self.HoutModelLastWeek = [HOutputModel yy_modelWithJSON:tempData];
        self.HoutModelLastWeek.title = @"上周";

    }];
    NSString *url2 = F(@"%@/counts/output?start_time=%@&end_time=%@", BaseUrl,[self getNDay:-29]?:@"",[self getNDay:1]?:@"");
    [self receivePOSTWithTokenURLString:url2 method:@"GET" body:nil Token:Token Blocks:^(NSDictionary *tempData, NSInteger state) {
        self.HoutModelLastMonth = [HOutputModel yy_modelWithJSON:tempData];
        self.HoutModelLastMonth.title = @"上月";

    }];
    NSString *url3 = F(@"%@/counts/output", BaseUrl);
    [self receivePOSTWithTokenURLString:url3 method:@"GET" body:nil Token:Token Blocks:^(NSDictionary *tempData, NSInteger state) {
        self.HoutModel = [HOutputModel yy_modelWithJSON:tempData];
        self.HoutModel.title = @"总计";
    }];
    [self.modelArray addObject:self.HoutModelYesterDay];
    [self.modelArray addObject:self.HoutModelLastWeek];
    [self.modelArray addObject:self.HoutModelLastMonth];
    [self.modelArray addObject:self.HoutModel];
}
//产品趋势
- (void)GetTrend {
    NSString *url = F(@"%@/outputs/trend?start_time=%@&end_time=%@", BaseUrl,[self getNDay:-7]?:@"",[self getNDay:0]?:@"");
    NSString *Token = F(@"Token %@",  [[TMCache sharedCache] objectForKey:@"Token"]);
    [self receivePOSTWithTokenURLString:url method:@"GET" body:nil Token:Token Blocks:^(NSDictionary *tempData, NSInteger state) {
        NSArray *TempArray  = (NSArray *)tempData;
        for (NSString *obj in [self latelySevenTime]) {
            if (TempArray.count > 0) {
                for (NSDictionary *dic in tempData) {
                    if ([[dic objectForKey:@"date_time"] isEqualToString:obj]) {
                        [self.tendArray addObject:[dic objectForKey:@"average"]];
                        break;
                    }else if ([[TempArray objectAtIndex:TempArray.count - 1] isEqual:dic]){
                        [self.tendArray addObject:@(0)];
                        break;
                    }
                }
            }else {
                [self.tendArray addObject:@(0)];
            }
        }
    }];
}
//路由数量统计
- (void)GetRouter {
    NSString *url = F(@"%@/counts/router", BaseUrl);
    NSString *Token = F(@"Token %@",[[TMCache sharedCache] objectForKey:@"Token"]);
    [self receivePOSTWithTokenURLString:url method:@"GET" body:nil Token:Token Blocks:^(NSDictionary *tempData, NSInteger state) {
        self.routerModel = [HRouterModel yy_modelWithJSON:tempData];
        [self.tabelview reloadData];
    }];
}

- (UITableView *)tabelview {
    if (!_tabelview) {
        _tabelview = [[UITableView alloc]initWithFrame:CGRectMake(0, NavBarHeight, ScreenWidth, ScreenHeight - NavBarHeight) style:UITableViewStylePlain];
        _tabelview.dataSource = self;
        _tabelview.delegate = self;
        [_tabelview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CellID"];
        _tabelview.backgroundColor = kBackGroundColor;
        _tabelview.separatorColor = [UIColor colorWithCGColor:[kStrokeBackGroundColor CGColor]];
        _tabelview.tableFooterView = [[UIView alloc]init];
    }
    return _tabelview;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    self.tabelHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth , ScreenHeight - NavBarHeight)];
    self.tabelHeaderView.backgroundColor = kBackGroundColor;
    XLCycleCollectionView*cyleView = [[XLCycleCollectionView alloc] initWithFrame:CGRectMake(15,  15, self.tabelHeaderView.width - 30, 150)];
    cyleView.data = (NSArray *)self.modelArray;
    [self.tabelHeaderView addSubview:cyleView];

    [self.tabelHeaderView addSubview:self.collectionView];
    UILabel *timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 170 + 5, ScreenWidth - 20, 20)];
    timeLabel.textColor = kTitleBackGroundColor;
    timeLabel.font = [UIFont fontWithName:PingFangSCRegular size:14];
    timeLabel.text = [NSString stringWithFormat:@"实时数据更新时间：%@",[self getNDay:0]];
    [self.tabelHeaderView addSubview:timeLabel];
    
    self.chartView = [[TWRChartView alloc] initWithFrame:CGRectMake(15, self.collectionView.bottom + 10, ScreenWidth - 30, 200)];
    self.chartView.backgroundColor = kWidgetBackGroundColor;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(_chartView.width - 150, 10,140, 20)];
    label.textColor = kTitleBackGroundColor;
    label.font = [UIFont fontWithName:PingFangSCRegular size:14];
    label.text = @"平均产量走势图";
    [self.chartView addSubview:label];
    [self.tabelHeaderView addSubview:self.chartView];
    [self loadLineChart];
    //创建饼状图
    self.pieChartView = [[PieChartView alloc] initWithFrame:CGRectMake(15, _chartView.bottom + 10, ScreenWidth / 3 * 2,200)];
    self.pieChartView.backgroundColor = kWidgetBackGroundColor;
    [self.view addSubview:self.pieChartView];
    UIView *hiddenView = [[UIView alloc]initWithFrame:CGRectMake(0, self.pieChartView.height - 30, self.pieChartView.width, 30)];
    hiddenView.backgroundColor = kWidgetBackGroundColor;
    [self.pieChartView addSubview:hiddenView];
  
    //基本样式
    [self.pieChartView setExtraOffsetsWithLeft:30 top:10 right:30 bottom:0];//饼状图距离边缘的间隙
    self.pieChartView.usePercentValuesEnabled = YES;//是否根据所提供的数据, 将显示数据转换为百分比格式
    self.pieChartView.dragDecelerationEnabled = NO;//拖拽饼状图后是否有惯性效果
    self.pieChartView.drawCenterTextEnabled = NO;//是否显示区块文本
    self.pieChartView.chartDescription.enabled = NO;//饼状图描述
    //空心饼状图样式
    self.pieChartView.drawHoleEnabled = YES;//饼状图是否是空心
    self.pieChartView.holeRadiusPercent = 0.5;//空心半径占比
    self.pieChartView.holeColor = [UIColor clearColor];//空心颜色
    self.pieChartView.transparentCircleRadiusPercent = 0.52;//半透明空心半径占比
    self.pieChartView.transparentCircleColor = [UIColor colorWithRed:210/255.0 green:145/255.0 blue:165/255.0 alpha:0.3];//半透明空心的颜色
    self.pieChartView.legend.maxSizePercent = 1;//图例在饼状图中的大小占比, 这会影响图例的宽高
    self.pieChartView.legend.formToTextSpace = 5;//文本间隔
    self.pieChartView.legend.font = [UIFont systemFontOfSize:10];//字体大小
    self.pieChartView.legend.textColor = [UIColor grayColor];//字体颜色
    self.pieChartView.legend.form = ChartLegendFormCircle;//图示样式: 方形、线条、圆形
    self.pieChartView.legend.formSize = 12;//图示大小
    //为饼状图提供数据
    self.data = [self setData];
    self.pieChartView.data = self.data;
    //设置动画效果
    [self.pieChartView animateWithXAxisDuration:1.0f easingOption:ChartEasingOptionEaseOutExpo];
    [self.tabelHeaderView addSubview:self.pieChartView];
    [self setView];
    return self.tabelHeaderView;
}
//设置饼状图描述
- (void)setView {
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth / 3 * 2, self.pieChartView.top, (ScreenWidth - 15 - (ScreenWidth / 3 * 2 )) , 200)];
    view.backgroundColor = kWidgetBackGroundColor;
    for (int i = 0; i < 3; i ++) {
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(15, 20 * i + 15, 15, 15)];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(image.right + 5, 20 * i + 15, 50, 15)];
        label.textColor = kTitleBackGroundColor;
        label.font = [UIFont fontWithName:PingFangSCRegular size:12];
        image.layer.masksToBounds = YES;
        image.layer.cornerRadius = 7.5;
        if (i == 0) {
            image.backgroundColor = [Networking colorWithHexString:@"#32BFA3"];
            label.text = @"在线统计";
        }else if (i == 1) {
            image.backgroundColor = [Networking colorWithHexString:@"#F5506B"];
            label.text = @"掉盘统计";
        }else if (i == 2) {
            image.backgroundColor = [Networking colorWithHexString:@"#716ACA"];
            label.text = @"离线统计";
        }
        [view addSubview:image];
        [view addSubview:label];
    }
    view.centerY = self.pieChartView.centerY;
    [self.tabelHeaderView addSubview:view];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID" forIndexPath:indexPath];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (iPhone6) {
        return ScreenHeight * 1.3;
    }else if (iPhone6plus){
        return ScreenHeight * 1.2;
    }else if (iPhone5) {
        return ScreenHeight * 1.5;
    }
    return ScreenHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        NSString *deviceType = [UIDevice currentDevice].model;
        UICollectionViewFlowLayout *flowLayOut = [[UICollectionViewFlowLayout alloc]init];
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(5,200, ScreenWidth - 10,220) collectionViewLayout:flowLayOut];
        flowLayOut.minimumInteritemSpacing = 5;
        flowLayOut.minimumLineSpacing = 5;
        flowLayOut.scrollDirection = UICollectionViewScrollDirectionVertical;//V 竖直方向  H 水平方向
        if (iPhone6plus) {
            flowLayOut.sectionInset = UIEdgeInsetsMake(1, 5, 5, 5);
            flowLayOut.itemSize = CGSizeMake(194, 100);
        }else if (iPhone6){
            flowLayOut.sectionInset = UIEdgeInsetsMake(1, 10, 10, 10);
            flowLayOut.itemSize = CGSizeMake(170, 100);
        } else if (iPhone5) {
            flowLayOut.sectionInset = UIEdgeInsetsMake(1, 10, 10, 10);
            flowLayOut.itemSize = CGSizeMake(142, 100);
        } else if ([deviceType isEqualToString:@"iPad"]) {
            flowLayOut.sectionInset = UIEdgeInsetsMake(5, 5, 5, 30);
            flowLayOut.itemSize = CGSizeMake(ScreenWidth / 2 - 30 ,100);
        }
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.scrollEnabled = NO;
        [_collectionView registerClass:[HHomeCollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
    }
    return _collectionView;
}

- (NSInteger )collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HHomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    cell.backgroundColor = kWidgetBackGroundColor;
    if (indexPath.row == 0) {
        cell.IconImage.image = [UIImage imageNamed:@"设备"];
        cell.commentLabel.text = @"设备总量";
        cell.numberLabel.text = [NSString stringWithFormat:@"%ld",(long)self.routerModel.total];
    }if (indexPath.row == 1) {
        cell.IconImage.image = [UIImage imageNamed:@"在线"];
        cell.commentLabel.text = @"在线统计";
        cell.numberLabel.text = [NSString stringWithFormat:@"%ld",(long)self.routerModel.work];
    }
    if (indexPath.row == 2) {
        cell.IconImage.image = [UIImage imageNamed:@"分盘"];
        cell.commentLabel.text = @"掉盘统计";
        cell.numberLabel.text = [NSString stringWithFormat:@"%ld",(long)self.routerModel.out_of_disk];
    }
    if (indexPath.row == 3) {
        cell.IconImage.image = [UIImage imageNamed:@"离线"];
        cell.commentLabel.text = @"离线统计";
        cell.numberLabel.text = [NSString stringWithFormat:@"%ld",(long)self.routerModel.outline];
    }
    return  cell;
}
- (NSInteger )numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (void)loadLineChart {//曲线图
    TWRDataSet *dataSet = [[TWRDataSet alloc] initWithDataPoints:(NSArray *)self.tendArray];
    dataSet.strokeColor = kNavBlueColor;
    dataSet.fillColor = [UIColor colorWithRed:64 / 255.0 green:158 / 255.0 blue:255 / 255.0 alpha:0.1];
    dataSet.pointColor = kNavBlueColor;
    NSArray *label = (NSArray *)[self latelySevenTime];
    TWRLineChart *line = [[TWRLineChart alloc] initWithLabels:label
                                                     dataSets:@[dataSet]
                                                     animated:NO];
    [self.chartView loadLineChart:line];
}

- (void)updateData{
    //为饼状图提供数据
    self.data = [self setData];
    self.pieChartView.data = self.data;
    //设置动画效果
    [self.pieChartView animateWithXAxisDuration:1.0f easingOption:ChartEasingOptionEaseOutExpo];
}
- (PieChartData *)setData{
    //每个区块的数据
    NSMutableArray *yVals = [[NSMutableArray alloc] init];
    NSArray *array = @[@(self.routerModel.work),@(self.routerModel.out_of_disk),@(self.routerModel.outline)];
    for (int i = 0; i < array.count; i++) {
        double randomVal = [array[i]floatValue];
        [yVals addObject:[[PieChartDataEntry alloc]initWithValue:randomVal]];
    }
    PieChartDataSet *dataSet = [[PieChartDataSet alloc]initWithValues:yVals label:@""];
    dataSet.drawValuesEnabled = YES;//是否绘制显示数据
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors addObject:[Networking colorWithHexString:@"#32BFA3"]];
    [colors addObject:[Networking colorWithHexString:@"#F5506B"]];
    [colors addObject:[Networking colorWithHexString:@"#716ACA"]];

    dataSet.colors = colors;//区块颜色
    dataSet.sliceSpace = 0;//相邻区块之间的间距
    dataSet.selectionShift = 8;//选中区块时, 放大的半径
    dataSet.xValuePosition = 1;//名称位置
    dataSet.yValuePosition = 1;//数据位置
    //数据与区块之间XXXX的用于指示的折线样式
    dataSet.valueLinePart1OffsetPercentage = 0.85;//折线中第一段起始位置相对于区块的偏移量, 数值越大, 折线距离区块越远
    dataSet.valueLinePart1Length = 0.5;//折线中第一段长度占比
    dataSet.valueLinePart2Length = 0.4;//折线中第二段长度最大占比
    dataSet.valueLineWidth = 1;//折线的粗细
    dataSet.valueLineColor = kTitleBackGroundColor;//折线颜色

    PieChartData *data = [[PieChartData alloc]initWithDataSet:dataSet];
    NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterPercentStyle;
    formatter.maximumFractionDigits = 2;//小数位数
    formatter.multiplier = @1.f;
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:formatter]];
    [data setValueTextColor:kTitleBackGroundColor];
    [data setValueFont:[UIFont systemFontOfSize:10]];
    return data;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
